<?php
/**
 * WebSocket语音播报系统检查工具
 * 检查所有必要的文件和服务是否就绪
 */

echo "========================================\n";
echo "  WebSocket语音播报系统检查\n";
echo "========================================\n\n";

$errors = [];
$warnings = [];
$success = [];

// 1. 检查核心文件
echo "[1/6] 检查核心文件...\n";

$requiredFiles = [
    'websocket_server.php' => 'WebSocket服务器主程序',
    'tools/device_tcp/simple_server.php' => 'TCP设备服务器',
    'public/voice_player.html' => '语音播报前端页面',
    'start_all_servers.bat' => '启动脚本',
    'test_websocket_push.php' => '测试推送脚本'
];

foreach ($requiredFiles as $file => $desc) {
    if (file_exists($file)) {
        $success[] = "  ✓ {$desc}: {$file}";
    } else {
        $errors[] = "  ✗ {$desc}不存在: {$file}";
    }
}

echo implode("\n", $success) . "\n";
if (!empty($errors)) {
    echo implode("\n", $errors) . "\n";
}
echo "\n";

// 2. 检查语音文件目录
echo "[2/6] 检查语音文件目录...\n";

$voiceDir = 'public/static/voice';
if (!is_dir($voiceDir)) {
    $errors[] = "  ✗ 语音文件目录不存在: {$voiceDir}";
    echo "  ✗ 语音文件目录不存在\n";
} else {
    echo "  ✓ 语音文件目录存在\n";
    
    // 检查音频文件
    $voiceFiles = [
        'success.mp3' => '签到成功',
        'end.mp3' => '结束签到',
        'duplicate.mp3' => '重复刷脸'
    ];
    
    $missingVoices = [];
    foreach ($voiceFiles as $file => $desc) {
        $path = "{$voiceDir}/{$file}";
        if (file_exists($path)) {
            $size = filesize($path);
            $sizeKB = round($size / 1024, 2);
            echo "  ✓ {$desc}: {$file} ({$sizeKB} KB)\n";
        } else {
            $missingVoices[] = "  ⚠ {$desc}音频文件不存在: {$file}";
        }
    }
    
    if (!empty($missingVoices)) {
        echo implode("\n", $missingVoices) . "\n";
        $warnings[] = "语音文件缺失，请参考 public/static/voice/README.md 准备音频文件";
    }
}
echo "\n";

// 3. 检查Workerman扩展
echo "[3/6] 检查PHP扩展...\n";

$requiredExtensions = [
    'sockets' => 'Socket扩展（Workerman需要）',
    'pcntl' => 'PCNTL扩展（进程控制，Windows不需要）',
    'posix' => 'POSIX扩展（Windows不需要）'
];

foreach ($requiredExtensions as $ext => $desc) {
    if (extension_loaded($ext)) {
        echo "  ✓ {$desc}\n";
    } else {
        if (PHP_OS_FAMILY === 'Windows' && in_array($ext, ['pcntl', 'posix'])) {
            echo "  ⚠ {$desc} (Windows系统不需要)\n";
        } else {
            $warnings[] = "  ⚠ {$desc}未安装";
            echo "  ⚠ {$desc}未安装\n";
        }
    }
}
echo "\n";

// 4. 检查端口占用
echo "[4/6] 检查端口占用...\n";

$ports = [
    8778 => 'TCP设备服务器',
    8779 => 'WebSocket服务器',
    8780 => '内部通信端口'
];

foreach ($ports as $port => $desc) {
    $socket = @stream_socket_client("tcp://127.0.0.1:{$port}", $errno, $errstr, 1);
    if ($socket) {
        echo "  ✓ 端口 {$port} ({$desc}) - 服务已启动\n";
        fclose($socket);
    } else {
        echo "  ⚠ 端口 {$port} ({$desc}) - 服务未启动\n";
        $warnings[] = "端口 {$port} ({$desc}) 未启动";
    }
}
echo "\n";

// 5. 检查Workerman是否已安装
echo "[5/6] 检查Workerman框架...\n";

if (file_exists('vendor/workerman/workerman/Worker.php')) {
    echo "  ✓ Workerman框架已安装\n";
    
    // 检查版本
    require_once 'vendor/autoload.php';
    if (class_exists('Workerman\Worker')) {
        $version = defined('Workerman\Worker::VERSION') ? constant('Workerman\Worker::VERSION') : '未知';
        echo "  ✓ Workerman版本: {$version}\n";
    }
} else {
    $errors[] = "  ✗ Workerman框架未安装";
    echo "  ✗ Workerman框架未安装\n";
    echo "  提示：运行 composer require workerman/workerman\n";
}
echo "\n";

// 6. 检查simple_server.php是否包含WebSocket推送代码
echo "[6/6] 检查TCP服务器WebSocket集成...\n";

$serverFile = 'tools/device_tcp/simple_server.php';
if (file_exists($serverFile)) {
    $content = file_get_contents($serverFile);
    
    if (strpos($content, 'pushToWebSocket') !== false) {
        echo "  ✓ TCP服务器已集成WebSocket推送功能\n";
    } else {
        $errors[] = "  ✗ TCP服务器未集成WebSocket推送功能";
        echo "  ✗ TCP服务器未集成WebSocket推送功能\n";
    }
    
    if (strpos($content, 'playVoice') !== false) {
        echo "  ✓ TCP服务器包含语音播放函数\n";
    } else {
        $errors[] = "  ✗ TCP服务器缺少语音播放函数";
        echo "  ✗ TCP服务器缺少语音播放函数\n";
    }
} else {
    $errors[] = "  ✗ TCP服务器文件不存在";
    echo "  ✗ TCP服务器文件不存在\n";
}
echo "\n";

// 总结
echo "========================================\n";
echo "  检查结果\n";
echo "========================================\n\n";

if (empty($errors) && empty($warnings)) {
    echo "✅ 所有检查通过！系统已就绪。\n\n";
    
    echo "下一步操作：\n";
    echo "1. 启动服务：双击运行 start_all_servers.bat\n";
    echo "2. 打开页面：http://localhost:8000/voice_player.html\n";
    echo "3. 测试推送：php test_websocket_push.php success\n";
    
} else {
    if (!empty($errors)) {
        echo "❌ 发现 " . count($errors) . " 个错误：\n";
        foreach ($errors as $error) {
            echo $error . "\n";
        }
        echo "\n";
    }
    
    if (!empty($warnings)) {
        echo "⚠️  发现 " . count($warnings) . " 个警告：\n";
        foreach ($warnings as $warning) {
            echo $warning . "\n";
        }
        echo "\n";
    }
    
    echo "建议：\n";
    
    if (!empty($errors)) {
        echo "1. 解决上述错误后再启动系统\n";
    }
    
    if (in_array("语音文件缺失，请参考 public/static/voice/README.md 准备音频文件", $warnings)) {
        echo "2. 准备音频文件（参考 public/static/voice/README.md）\n";
    }
    
    if (strpos(implode('', $warnings), '服务未启动') !== false) {
        echo "3. 运行 start_all_servers.bat 启动服务\n";
    }
}

echo "\n";
echo "========================================\n";
echo "  详细文档\n";
echo "========================================\n";
echo "查看完整使用说明：WEBSOCKET_VOICE_GUIDE.md\n";
echo "查看音频文件说明：public/static/voice/README.md\n";
echo "\n";

